﻿using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.StackExchangeRedis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Niaofei.Redis
{
    public static class RedisExtension
    {
        /// <summary>
        /// redis服务添加
        /// </summary>
        /// <param name="services">服务容器</param>
        /// <param name="cacheOptions">redis选项配置</param>
        public static void AddRedisCache(this IServiceCollection services, Action<RedisCacheOptions>? cacheOptions = null)
        {
            AddRedisDatabase(services);

            AddRedisService(services, cacheOptions);
        }

        private static void AddRedisService(IServiceCollection services, Action<RedisCacheOptions>? cacheOptions)
        {
            if (cacheOptions == null)
            {
                var provider = services.BuildServiceProvider();

                var configuration = provider.GetRequiredService<IConfiguration>();

                var redisEnabled = configuration["Redis:IsEnabled"];

                if (!string.IsNullOrEmpty(redisEnabled) || bool.Parse(redisEnabled ?? "false"))
                {
                    services.AddStackExchangeRedisCache(options =>
                    {
                        var redisConfiguration = configuration["Redis:Configuration"];
                        if (!string.IsNullOrEmpty(redisConfiguration))
                        {
                            options.InstanceName = "Niaofei";
                            options.Configuration = redisConfiguration;
                        }
                    });
                }
            }
            else
            {
                services.AddStackExchangeRedisCache(cacheOptions);
            }

            services.AddSingleton(typeof(IDistributedCache<>), typeof(DistributedCache<>));
            services.AddSingleton(typeof(IDistributedCache<,>), typeof(DistributedCache<,>));
        }

        private static void AddRedisDatabase(IServiceCollection services)
        {
            services.AddTransient(provider =>
            {
                var configuration = provider.GetRequiredService<IConfiguration>();

                var redisConfiguration = configuration["Redis:Configuration"];

                return ConnectionMultiplexer.Connect(redisConfiguration);
            });
        }
    }
}
